/*
 * Copyright 2015 泛泛o0之辈
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.jfast.framework.jdbc.db;

import cn.jfast.framework.base.util.ObjectUtils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

/**
 * 从数据源或者DriverManager中获取数据库链接

 * @author 泛泛o0之辈
 */
public class DatabaseConfiguration {

    private static DataSource dataSource;
	private static Connection conn;

	protected static Connection configure() throws ClassNotFoundException, SQLException {
		if (ObjectUtils.isNull(dataSource)) {
			try {
				Class.forName("com.alibaba.druid.pool.DruidDataSource");
				AlibabaDruidDataSource druidDataSource = new AlibabaDruidDataSource();
				if (druidDataSource.init()) 
					dataSource = druidDataSource.getDataSource();
			} catch (ClassNotFoundException e) {
				try {
					Class.forName("com.mchange.v2.c3p0.ComboPooledDataSource");
					C3p0DataSource c3poDataSource = new C3p0DataSource();
					if (c3poDataSource.init()) 
						dataSource = c3poDataSource.getDataSource();
				} catch (ClassNotFoundException e1) {
					try {
						Class.forName("org.apache.commons.dbcp.BasicDataSource");
						DbcpDataSource dbcpDataSource = new DbcpDataSource();
						if (dbcpDataSource.init()) 
							dataSource = dbcpDataSource.getDataSource();
					} catch (ClassNotFoundException e2) {
						conn = DriverManageConnFactory.me().getConnection();
					}
				}
			}
		}
		if (null != dataSource)
			conn = dataSource.getConnection();
		return conn;
	}

	protected DataSource getDataSource() {
		return dataSource;
	}

}
